const path = require('path');
const fs = require('fs');
const Router = require('koa-router');
const router = new Router();

const route = require('../route');

module.exports = app => {
    let routeCacheList=[],
        getRouteCache = {},
        currentPath = path.resolve(__dirname, "../controllers"),
        directories = fs.readdirSync(currentPath);
    for (let dir of directories) {
        routeCacheList.push(path.join(currentPath, dir))
    }
    routeCacheList.forEach((routePath) => {
        let routeFun = require(routePath);
        let routeName = Object.keys(routeFun).toString();
        getRouteCache[routeName] = routeFun;
    });

    route.forEach((singRoute, index) => {
        let { match, controller } = singRoute;
        let controllerList = controller.split('.');
        router.get(singRoute.match, getRouteCache[controllerList[0]][controllerList[1]]);
    });

    app
        .use(router.routes())
        .use(router.allowedMethods());
};
